<template>
  <view class="content padd20">
    <view class="zjsc">
      <!-- <image class="cover-img" :src="imagesIcon[0]"  mode="aspectFill"></image> -->
      身份证(必填)
    </view>
    <view class="box-content padtb30">
      <view class="ghmsc">
        <view class="sctp" @click="selectIdFace">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathFace[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{ showBackWord1 ? '重新上传' : '点击上传人像面' }}</view>
          </view>
        </view>
        <view class="sctp" @click="selectCardBack">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathBack[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{ showBackWord2 ? '重新上传' : '点击上传国徽面' }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="box-content">
      <view class="qrsf">
        <view class="sjxx">
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>个人姓名</view>
            <input class="uni-input" v-model="driverInfo.driverName" maxlength="50" />
          </view>

          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>身份证号</view>
            <input class="uni-input" v-model="driverInfo.idNo" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>有效期起</view>
            <w-picker :visible="dateStart1" mode="date" startYear="1900" endYear="2124" :value="dateStart1Show"
              :current="false" fields="day" @confirm="onConfirm1($event, 'date1')" @cancel="onCancel1"
              :disabled-after="false" ref="date1"></w-picker>
            <input class="uni-input prd-mess" v-model="dateStart1Show" placeholder="有效期起" disabled="true"
              @click="dateStart1 = true"></input>
          </view>
          <view class="uni-form-item no-border">
            <view class="title"><span style="color:red;">*</span>有效期止：</view>
            <w-picker :visible="dateEnd1" mode="date" startYear="1900" endYear="2124" :value="dateEnd1Show"
              :current="false" fields="day" @confirm="onConfirm2($event, 'date1')" @cancel="onCancel2"
              :disabled-after="false" ref="date1"></w-picker>
            <input class="uni-input prd-mess" v-model="dateEnd1Show" placeholder="有效期止" disabled="true"
              @click="dateEnd1 = true"></input>
          </view>
        </view>
      </view>
    </view>


    <view class="zjsc">
      <!-- <image class="cover-img" :src="imagesIcon[0]"  mode="aspectFill"></image> -->
      驾驶证(必填)
    </view>
    <view class="box-content padtb30">
      <view class="ghmsc">
        <view class="sctp" @click="selectLicenseFace">
          <view class="img-box">
            <image class="cover-img" :src="imagesLicenseFace[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{ showBackWord3 ? '重新上传' : '点击上传驾驶证正面' }}</view>
          </view>
        </view>
        <view class="sctp" @click="selectLicenseBack">
          <view class="img-box">
            <image class="cover-img" :src="imagesLicenseBack[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{ showBackWord4 ? '重新上传' : '点击上传驾驶证背面' }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="box-content">
      <view class="qrsf">
        <view class="sjxx">
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>驾驶证号</view>
            <input class="uni-input" v-model="driverInfo.licenseNo" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>准驾车型</view>
            <view class="uni-select-box">
              <!-- <picker @change="confirmChange" :value="driverInfo.licenseType" mode="selector" :range="cartypeDatas" range-key="text">
								<view class="uni-input">{{driverInfo.licenseType || ''}}</view>
						    </picker> -->
              <view class="uni-input" @click="showPop">{{ driverInfo.licenseType || '' }}</view>
              <uni-icons type="forward" size="20"></uni-icons>
            </view>
            <uv-picker ref="selectBoxPop" :confirmColor="curColor" :columns="cartypeDatas" keyName="label"
              @confirm="confirmPop"></uv-picker>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>发证机关</view>
            <input class="uni-input" v-model="driverInfo.licenceIssuingAuthority" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>初次申领日期</view>
            <w-picker :visible="dateStart4" mode="date" startYear="1900" endYear="2124" :value="initialDateShow"
              :current="false" fields="day" @confirm="onConfirm7($event, 'date1')" @cancel="onCancel7"
              :disabled-after="false" ref="date1"></w-picker>
            <input class="uni-input prd-mess" v-model="initialDateShow" placeholder="初次申领日期" disabled="true"
              @click="dateStart4 = true"></input>
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>有效期起</view>
            <w-picker :visible="dateStart2" mode="date" startYear="1900" endYear="2124" :value="dateStart2Show"
              :current="false" fields="day" @confirm="onConfirm3($event, 'date1')" @cancel="onCancel3"
              :disabled-after="false" ref="date1"></w-picker>
            <input class="uni-input prd-mess" v-model="dateStart2Show" placeholder="有效期起" disabled="true"
              @click="dateStart2 = true"></input>
          </view>
          <view class="uni-form-item no-border">
            <view class="title"><span style="color:red;">*</span>有效期止</view>
            <w-picker :visible="dateEnd2" mode="date" startYear="1900" endYear="2124" :value="dateEnd2Show"
              :current="false" fields="day" @confirm="onConfirm4($event, 'date1')" @cancel="onCancel4"
              :disabled-after="false" ref="date1"></w-picker>
            <input class="uni-input prd-mess" v-model="dateEnd2Show" placeholder="有效期止" disabled="true"
              @click="dateEnd2 = true"></input>
          </view>
        </view>
      </view>
    </view>


    <view class="zjsc">
      <!-- <image class="cover-img" :src="imagesIcon[0]"  mode="aspectFill"></image> -->
      道路资格证信息(必填)
    </view>
    <view class="box-content padtb30">
      <view class="ghmsc">
        <view class="sctp" @click="selectRoadFace">
          <view class="img-box">
            <image class="cover-img" :src="imagesPathRoad[0]" mode="aspectFill"></image>
            <image class="cover-imgs" :src="imagesCamera" mode="aspectFill"></image>
            <view class="img-text">{{ showBackWord5 ? '重新上传' : '点击上传道路资格证' }}</view>
          </view>
        </view>
      </view>
    </view>
    <view class="box-content">
      <view class="qrsf">
        <view class="sjxx">
          <view class="uni-form-item">
            <view class="title" style="width: 199rpx;"><span style="color:red;">*</span>从业资格证号</view>
            <input class="uni-input" v-model="driverInfo.roadCertNo" maxlength="50" />
          </view>
          <view class="uni-form-item">
            <view class="title"><span style="color:red;">*</span>有效期起</view>
            <w-picker :visible="dateStart3" mode="date" startYear="1900" endYear="2124"
              :value="driverInfo.roadQualificationCertificateStartDate" :current="false" fields="day"
              @confirm="onConfirm5($event)" @cancel="onCancel5" :disabled-after="false"></w-picker>
            <input class="uni-input prd-mess" v-model="driverInfo.roadQualificationCertificateStartDate"
              placeholder="有效期起" disabled="true" @click="dateStart3 = true" />
          </view>
          <view class="uni-form-item no-border">
            <view class="title"><span style="color:red;">*</span>有效期止</view>
            <w-picker :visible="dateEnd3" mode="date" startYear="1900" endYear="2124"
              :value="driverInfo.roadQualificationCertificateEndDate" :current="false" fields="day"
              @confirm="onConfirm6($event)" @cancel="onCancel6" :disabled-after="false"></w-picker>
            <input class="uni-input prd-mess" v-model="driverInfo.roadQualificationCertificateEndDate"
              placeholder="有效期止" disabled="true" @click="dateEnd3 = true" />
          </view>
        </view>
      </view>
    </view>

    <view class="box-content" style="margin-bottom: 155rpx;">
      <view style="padding: 30rpx 0;">
        <view class="zysx">
          <view class="title">注意事项：</view>
          <view class="list">1、同一个身份证号只能认证一个账号；</view>
          <view class="list">2、国徽面与正面信息应为同一身份证的信息且在有效期内；</view>
          <view class="list">3、所有上传照片需清晰且未遮挡，请勿进行美化和修改；</view>
        </view>
      </view>
    </view>

    <view class="btns" v-if="mtype == 'update'">
      <button :class="{ loading: isLoading }" type="primary" @click.native="handleSubmit">
        提交
        <view v-if="isLoading" class="loading-icon"></view>
      </button>
    </view>
    <view v-else class="btns">
      <button :class="{ loading: isLoading }" type="primary" @click.native="handleSubmit">
        提交
        <view v-if="isLoading" class="loading-icon"></view>
      </button>
    </view>
  </view>
</template>
<script>
  import func from '@/utils/funlogin.js';
  import { getOpenIdByCode } from '@/api/login.js';
  import {
    getDriving,
    updateDriving,
    getDrivingRecognize,
    getIdcardRecognize,
    getDictDatas
  } from '@/api/me.js';
  import {
    getAccessToken,
    getOpenId,
    getDriverId
  } from '@/utils/auth';
  import {
    dictTansParams,
    getDate,
    timestampToChineseDate,
    toast,
    compressImage,
    compressImg
  } from '@/utils/common.js';
  import config from '@/config'
  export default {
    data() {
      return {
        ysjhData: {}, // 从接单而来的参数
        showBackWord1: false,
        showBackWord2: false,
        showBackWord3: false,
        showBackWord4: false,
        showBackWord5: false,
        uploadImgMess1: false,
        uploadImgMess2: false,
        uploadImgMess3: false,
        uploadImgMess4: false,
        uploadImgMess5: false,
        dateStart1: false,
        dateEnd1: false,
        dateStart1Show: '',
        dateEnd1Show: '',
        dateStart2: false,
        dateEnd2: false,
        dateStart4: false,
        dateStart2Show: '',
        dateEnd2Show: '',
        initialDateShow: '',
        dateStart3: false,
        dateEnd3: false,
        cartypeDatas: [],
        dateRange: [],
        rangeTime: [],
        imagesLicenseFace: [config.baseImgUrl + '/driver-licenseFace1.png'],
        imagesLicenseBack: [config.baseImgUrl + '/road-transport.png'],
        mtype: 'update',
        isLoading: false,
        validateno: false,
        imagesIcon: [],
        imagesPathFace: [config.baseImgUrl + '/id-face.png'],
        imagesPathBack: [config.baseImgUrl + '/id-back.png'],
        imagesPathRoad: [config.baseImgUrl + '/road-transport.png'],
        driverInfo: {
          driverName: '',
          idNo: '',
          idAddress: '',
          birthdate: '',
          ethnicity: '',
          sex: '',
          issueAuthority: '',
          roadCertUrl: undefined,
          roadCertNo: undefined,
          roadQualificationCertificateStartDate: '',
          roadQualificationCertificateEndDate: '',
          drivingFaceUrl: undefined,
          drivingBackUrl: undefined,
          licenseEndDate: '',
          licenseStartDate: '',
          licenceIssuingAuthority: '',
          licenseType: '',
          licenseAddress: '',
          licenseBirthdate: '',
          licenseName: '',
          licenseSex: '',
          licenseNationality: '',
          licenseValidfromdate: '',
          licenseInitialissuedate: '',
          recordnumber: '',
          record: '',
          isLicenseIdentified: false, //驾驶证认证状态
          isRoadCertIdentified: false, //道路资格证认证状态
          id: '',
          licenseNo: '',
          startDate: '',
          endDate: '',
          isIdIdentified: false,
          idFaceUrl: undefined,
          idBackUrl: undefined,
          idCardLicenseFrontPic: undefined, //网货（卡漠）身份证正面图片
          idCardLicenseReversePic: undefined, //网货（卡漠）身份证背面图片
          drivingLicenseFrontPic: undefined, //网货（卡漠）驾驶证正面图片
          drivingLicenseReversePic: undefined, //网货（卡漠）驾驶证背面图片
          qualityCertPic: undefined, //网货（卡漠）道路从业资格证图片
          sync: false
        },
        faceUpload: false,
        backUpload: false,
        faceIdUpload: false,
        backIdUpload: false,
        type: '',
        errorMsg: '',
        dataSource: undefined
      };
    },
    onLoad(options) {
      if (!!options) {
        this.type = options.type
        this.dataSource = options.backType
      }
      this.getData();
      //获取字典
      this.getLicenseTypeDict()
    },
    computed: {
      curColor() {
        return this.$store.state.user.curTypeColor
      },
      imagesCamera() {
        if (this.$store.state.user.curTypeColor == "#D22C2C") {
          return config.baseImgUrl + '/camera1.png'
        } else if (this.$store.state.user.curTypeColor == "#409EFE") {
          return config.baseImgUrl + '/camera.png'
        } else { }
      },
    },
    methods: {

      showPop() {
        this.$refs['selectBoxPop'].open('bottom');
      },
      confirmPop(e) {
        if (this.cartypeDatas.length > 0) {
          this.driverInfo.licenseType = e.value[0].label
        }
      },
      confirmChange(e) {
        if (this.cartypeDatas.length > 0) {
          this.driverInfo.licenseType = this.cartypeDatas[e.detail.value].text
        }
      },
      onConfirm1(res, type) {
        this.dateStart1Show = res.result
        this.dateStart1 = false
      },
      onCancel1() {
        this.dateStart1 = false
      },
      onConfirm2(res, type) {
        this.dateEnd1Show = res.result
        this.dateEnd1 = false
      },
      onCancel2() {
        this.dateEnd1 = false
      },
      onConfirm3(res, type) {
        this.dateStart2Show = res.result
        this.dateStart2 = false
      },
      onCancel3() {
        this.dateStart2 = false
      },
      onConfirm7(res, type) {
        this.initialDateShow = res.result
        this.dateStart4 = false
      },
      onCancel7() {
        this.dateStart4 = false
      },
      onConfirm4(res, type) {
        this.dateEnd2Show = res.result
        this.dateEnd2 = false
      },
      onCancel4() {
        this.dateEnd2 = false
      },
      onConfirm5(res) {
        this.driverInfo.roadQualificationCertificateStartDate = res.result
        this.dateStart3 = false
      },
      onCancel5() {
        this.dateStart3 = false
      },
      onConfirm6(res) {
        this.driverInfo.roadQualificationCertificateEndDate = res.result
        this.dateEnd3 = false
      },
      onCancel6() {
        this.dateEnd3 = false
      },
      async getLicenseTypeDict() {
        let datas = await getDictDatas()
        this.cartypeDatas = [datas.data.filter(e => e.dictType === 'license_type')]
      },
      maskClick() {
        console.log('----maskClick事件');
      },
      changeCartype() { },
      //获取司机信息列表
      async getData() {
        try {
          let res = await getDriving();
          let _ = this
          if (res.code == 0) {
            if (!res.data) return
            _.driverInfo = res.data;

            if (!!res.data.licenseStartDate) {
              _.dateStart2Show = res.data.licenseStartDate
            }
            if (res.data.licenseFirstGetDate) {
              _.initialDateShow = res.data.licenseFirstGetDate
            }
            if (!!res.data.licenseEndDate) {
              if (res.data.licenseEndDate.includes('2999')) {
                _.dateEnd2Show = '2099-12-31'
              } else {
                _.dateEnd2Show = res.data.licenseEndDate
              }
            }
            if (!!res.data.startDate) _.dateStart1Show = res.data.startDate
            if (!!res.data.endDate) _.dateEnd1Show = res.data.endDate
            if (res.data.roadQualificationCertificateStartDate) {
              this.driverInfo.roadQualificationCertificateStartDate = res.data.roadQualificationCertificateStartDate
            }
            if (res.data.roadQualificationCertificateEndDate) {
              this.driverInfo.roadQualificationCertificateEndDate = res.data.roadQualificationCertificateEndDate
            }
            if (!!res.data.idFaceUrl) {
              _.showBackWord1 = true
              _.imagesPathFace = []
              _.imagesPathFace.push(res.data.idFaceUrl)
            }
            if (!!res.data.idBackUrl) {
              _.showBackWord2 = true
              _.imagesPathBack = []
              _.imagesPathBack.push(res.data.idBackUrl)
            }
            if (!!res.data.drivingBackUrl) {
              _.showBackWord4 = true
              _.imagesLicenseBack = []
              _.imagesLicenseBack.push(res.data.drivingBackUrl)
            }
            if (!!res.data.drivingFaceUrl) {
              _.showBackWord3 = true
              _.imagesLicenseFace = []
              _.imagesLicenseFace.push(res.data.drivingFaceUrl)
            }
            if (!!res.data.roadCertUrl) {
              _.showBackWord5 = true
              _.imagesPathRoad = []
              _.imagesPathRoad.push(res.data.roadCertUrl)
            }
          }
        } catch (e) {
          return false;
        }
      },
      // 提交司机信息
      async handleSubmit() {
        //校验参数
        let _ = this
        if (!_.driverInfo.idFaceUrl) {
          toast(`请上传身份证正面`);
          return
        }
        if (_.uploadImgMess1) {
          toast(`请上传合适的身份证正面`)
          return
        }
        if (!_.driverInfo.idBackUrl) {
          toast(`请上传身份证背面`);
          return
        }
        if (_.uploadImgMess2) {
          toast(`请上传合适的身份证背面`)
          return
        }
        if (!_.driverInfo.driverName) {
          toast(`个人姓名不能为空`);
          return
        }
        if (!/^[\u4E00-\u9FFF]+$/.test(_.driverInfo.driverName)) {
          toast(`个人姓名必须是汉字`);
          return
        }
        if (!_.driverInfo.idNo) {
          toast(`身份证号不能为空`);
          return
        }
        if (!_.dateStart1Show) {
          toast(`身份证有效期起不能为空`);
          return
        }
        const dateStart1Year = _.dateStart1Show?.split('-')?.[0]
        if (dateStart1Year?.length !== 4) {
          toast(`身份证有效期起日期格式错误`);
          return
        }
        if (!_.dateEnd1Show) {
          toast(`身份证有效期止不能为空`);
          return
        }
        const dateEnd1Year = _.dateEnd1Show?.split('-')?.[0]
        if (dateEnd1Year?.length !== 4) {
          toast(`身份证有效期止日期格式错误`);
          return
        }
        if (!_.driverInfo.drivingFaceUrl) {
          toast(`请上传驾驶证正面`);
          return
        }
        if (_.uploadImgMess3) {
          toast(`请上传合适的驾驶证正面`)
          return
        }
        if (!_.driverInfo.drivingBackUrl) {
          toast(`请上传驾驶证背面`);
          return
        }
        if (_.uploadImgMess4) {
          toast(`请上传合适的驾驶证背面`)
          return
        }
        if (!_.driverInfo.licenseNo) {
          toast(`驾驶证号不能为空`);
          return
        }
        if (!_.driverInfo.licenseType) {
          toast(`准驾车型不能为空`);
          return
        }
        if (!_.driverInfo.licenceIssuingAuthority) {
          toast(`发证机关不能为空`);
          return
        }
        if (!_.initialDateShow) {
          toast(`驾驶证初次领证日期不能为空`);
          return
        }
        const initialDateYear = _.initialDateShow?.split('-')?.[0]
        if (initialDateYear?.length !== 4) {
          toast(`驾驶证初次领证日期格式错误`);
          return
        }
        if (!_.dateStart2Show) {
          toast(`驾驶证有效期起不能为空`);
          return
        }
        const dateStart2Year = _.dateStart2Show?.split('-')?.[0]
        if (dateStart2Year?.length !== 4) {
          toast(`驾驶证有效期起日期格式错误`);
          return
        }
        if (!_.dateEnd2Show) {
          toast(`驾驶证有效期止不能为空`);
          return
        }
        const dateEnd2Year = _.dateEnd2Show?.split('-')?.[0]
        if (dateEnd2Year?.length !== 4) {
          toast(`驾驶证有效期止日期格式错误`);
          return
        }
        if (!_.driverInfo.roadCertUrl) {
          toast(`道路资格证图不能为空`);
          return
        }
        if (_.uploadImgMess5) {
          toast(`请上传合适的道路资格证`)
          return
        }
        if (!_.driverInfo.roadCertNo) {
          toast(`从业资格证号不能为空`);
          return
        }
        if (!_.driverInfo.roadQualificationCertificateStartDate) {
          toast('请选择从业资格证有效期起');
          return
        }
        if (!_.driverInfo.roadQualificationCertificateEndDate) {
          toast('请选择从业资格证有效期至');
          return
        }
        if (_.faceIdUpload && _.backIdUpload) _.driverInfo.isIdIdentified = true
        if (_.faceUpload && _.backUpload) _.driverInfo.isLicenseIdentified = true;

        _.driverInfo.endDate = _.dateEnd1Show
        _.driverInfo.startDate = _.dateStart1Show

        _.driverInfo.licenseFirstGetDate = _.initialDateShow
        _.driverInfo.licenseStartDate = _.dateStart2Show
        _.driverInfo.licenseEndDate = _.dateEnd2Show
        _.driverInfo.sync = true
        let data = _.driverInfo
        data.driverName = _.driverInfo.driverName
        data.mobile = _.driverInfo.mobile
        data.sync = _.driverInfo.sync
        this.isLoading = true
        //获取wx code
        let code1 = await func.wxLogin();
        let openid = await getOpenIdByCode(code1);
        data.openid = openid.data
        data.id = getDriverId()
        try {
          let res = await updateDriving(data);
          if (res.code == 0) {
            _.getUserInfor()
            uni.showToast({
              title: `更新成功`
            });
            if (_.type == 'code') {
              if (uni.getStorageSync('isSetSjxx') === 'net') {
                this.$tab.reLaunch('/pages/receivingNet?codes=true');
              } else if (uni.getStorageSync('isSetSjxx') === 'bj') {
                this.$tab.reLaunch('/pages/receivingBJ?codes=true');
              } else if (uni.getStorageSync('isSetSjxx') === 'jy') {
                this.$tab.reLaunch('/pages/receivingJY?codes=true');
              } else if (uni.getStorageSync('isSetSjxx') === 'jl') {
                this.$tab.reLaunch('/pages/receiving?codes=true');
              }
            } else {
              uni.switchTab({
                url: '/pages/mine/index'
              });
            }
          } else {
            toast(res.msg);
          }
        } finally {
          this.isLoading = false
        }
      },
      //获取司机用户信息
      async getUserInfor() {
        try {
          let res = await getDriving();
          if (res.code == 0) {
            console.log('实名后再次获取司机信息: ', res);
            if (!!res.data) {
              //存贮司机信息
              uni.setStorageSync('sjxxData', res.data);
            }
          }
        } catch (e) {
          return false;
        }
      },
      selectIdFace(e) {
        let _ = this
        //同时进行
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: (res) => {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                _.imagesPathFace = []
                _.imagesPathFace.push(resp.tempFilePath)
                _.uploadFilesKamo(resp.tempFilePath, 1)
                _.uploadFilesId(resp.tempFilePath, 1);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            console.log('上传身份证正面的照片fail：', e)
          }
        });
      },
      selectCardBack(e) {
        let _ = this
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                _.imagesPathBack = []
                _.imagesPathBack.push(resp.tempFilePath)
                _.uploadFilesKamo(resp.tempFilePath, 2)
                _.uploadFilesId(resp.tempFilePath, 2);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            console.log('上传身份证反面的照片fail：', e)
          }
        });
      },
      selectRoadFace(e) {
        let _ = this
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            if (curSize > 4 * 1024 * 1024) {
              toast("上传的图片不能超过4兆")
              return
            }
            let quelityVal = 100
            let initnum = 0.5 * 1024 * 1024
            console.log(curSize, "压缩前的大小=======")
            if (curSize > initnum) {
              quelityVal = Math.floor(100 / (curSize / initnum))
            }
            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                console.log(resp, "压缩后的大小=======")
                console.log(quelityVal, "压缩比例=======")
                _.imagesPathRoad = []
                _.imagesPathRoad.push(resp.tempFilePath)
                _.uploadFilesKamo(resp.tempFilePath, 5)
                _.uploadFilesId(resp.tempFilePath, 5);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            console.log('上传道路资格证的照片失败', e)
          }
        });
      },
      selectLicenseFace(e) {
        let _ = this
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                _.imagesLicenseFace = []
                _.imagesLicenseFace.push(resp.tempFilePath)
                _.uploadFilesKamo(resp.tempFilePath, 3)
                _.uploadFilesId(resp.tempFilePath, 3);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            console.log('上传身份证正面的照片fail：', e)
          }
        });
      },
      selectLicenseBack(e) {
        let _ = this
        uni.chooseImage({
          count: 1, //默认9
          sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], //从相册选择
          mediaType: ['image'],
          success: function (res) {
            let curSize = res.tempFiles[0].size
            let quelityVal = 100
            let initnum = 0.3 * 1024 * 1024
            if (curSize > initnum) {
              quelityVal = 100 / (curSize / initnum)
            }

            uni.compressImage({
              src: res.tempFilePaths[0],
              quelity: quelityVal,
              success: (resp) => {
                _.imagesLicenseBack = []
                _.imagesLicenseBack.push(resp.tempFilePath)
                _.uploadFilesKamo(resp.tempFilePath, 4)
                _.uploadFilesId(resp.tempFilePath, 4);
              },
              fail: (error) => { },
            })
          },
          fail(e) {
            console.log('上传身份证反面的照片fail：', e)
          }
        });
      },
      uploadFilesId(filepath, type) {
        wx.showLoading({
          title: '正在上传中...',
        });
        let _ = this

        uni.uploadFile({
          url: config.baseUrl + '/infra/file/upload',
          filePath: filepath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': 'Bearer ' + getAccessToken(),
          },
          async success(res) {
            wx.hideLoading()
            let msg = '',
              iconFlag = ''
            if (res.statusCode === 200) {
              if (type == 5) {
                _.uploadImgMess5 = false
                _.driverInfo.roadCertUrl = JSON.parse(res.data).data;
                //上传道路资格证
                if (JSON.parse(res.data).code == 0) {
                  msg = '上传成功'
                  _.driverInfo.isRoadCertIdentified = true
                } else {
                  msg = '上传失败'
                  _.driverInfo.isRoadCertIdentified = false
                }
              } else {
                let res1 = ''
                if (type == 1 || type == 2) {
                  res1 = await getIdcardRecognize(JSON.parse(res.data).data);
                  if (type == 1) _.driverInfo.idFaceUrl = JSON.parse(res.data).data;
                  else _.driverInfo.idBackUrl = JSON.parse(res.data).data;
                }
                if (type == 3 || type == 4) {
                  res1 = await getDrivingRecognize(JSON.parse(res.data).data);
                  if (type == 3) _.driverInfo.drivingFaceUrl = JSON.parse(res.data).data;
                  else _.driverInfo.drivingBackUrl = JSON.parse(res.data).data;
                }

                if (res1.code == 0) {
                  _.validateno = true
                  if (type == 1) { //身份证正面
                    _.uploadImgMess1 = false
                    _.showBackWord1 = true
                    if (!!res1.data.face) {
                      iconFlag = 'success'
                      msg = '上传成功'
                      _.driverInfo.driverName = (!!res1.data.face && res1.data.face.data
                        .name) || '';
                      _.driverInfo.idNo = (!!res1.data.face && res1.data.face.data
                        .idnumber) || '';
                      _.driverInfo.idAddress = (!!res1.data.face && res1.data.face.data
                        .address) || '';
                      _.driverInfo.birthdate = (!!res1.data.face && res1.data.face.data
                        .birthdate) || '';
                      _.driverInfo.sex = (!!res1.data.face && res1.data.face.data.sex) ||
                        '';
                      _.faceIdUpload = true
                    } else {
                      msg = '请上传身份证正面'
                      iconFlag = 'none'
                      _.errorMsg = '请上传身份证正面'
                      _.validateno = false
                      _.imagesPathFace = []
                      _.driverInfo.idFaceUrl = undefined
                      _.faceIdUpload = false
                    }
                  } else if (type == 2) { //身份证背面
                    _.showBackWord2 = true
                    _.uploadImgMess2 = false
                    if (!!res1.data.back) {
                      msg = '上传成功'
                      iconFlag = 'success'
                      _.driverInfo.issueAuthority = (!!res1.data.back && res1.data.back
                        .data.issueAuthority) || '';
                      let rangeTime = (!!res1.data.back && res1.data.back.data
                        .validPeriod) || '';
                      let tempDate = rangeTime.split("-")
                      const initialStartDateStr = tempDate[0].replaceAll(".", "-")
                      if (!isNaN(new Date(initialStartDateStr))) {
                        _.dateStart1Show = timestampToChineseDate(initialStartDateStr)
                      } else {
                        _.dateStart1Show = ''
                      }
                      if (tempDate[1].indexOf('长期') != -1) {
                        _.dateEnd1Show = '2099-12-31'
                      } else {
                        const initialEndDateStr = tempDate[1].replaceAll(".", "-")
                        if (!isNaN(new Date(initialEndDateStr))) {
                          _.dateEnd1Show = timestampToChineseDate(initialEndDateStr)
                        } else {
                          _.dateEnd1Show = ''
                          console.log('dateEnd1Show', _.dateEnd1Show)
                        }
                      }
                      _.backIdUpload = true
                    } else {
                      msg = '请上传身份证背面'
                      iconFlag = 'none'
                      _.errorMsg = '请上传身份证背面'
                      _.validateno = false
                      _.imagesPathBack = []
                      _.driverInfo.idBackUrl = undefined
                      _.backIdUpload = false
                    }
                  } else if (type == 3) { //驾驶证正面
                    _.uploadImgMess3 = false
                    iconFlag = 'success'
                    msg = '上传成功'
                    _.showBackWord3 = true
                    if (!!res1.data.face) {
                      _.driverInfo.licenseNo = (!!res1.data.face && res1.data.face.data
                        .licensenumber) || '';
                      _.driverInfo.licenseType = (!!res1.data.face && res1.data.face.data
                        .approvedtype) || '';
                      _.driverInfo.licenseAddress = (!!res1.data.face && res1.data.face
                        .data.address) || '';
                      _.driverInfo.licenseBirthdate = (!!res1.data.face && res1.data.face
                        .data.birthdate) || '';
                      const licenseDate = _.driverInfo.licenseBirthdate ?
                        timestampToChineseDate(_.driverInfo.licenseBirthdate) : '';
                      _.driverInfo.licenseBirthdate = licenseDate
                      _.driverInfo.licenseName = (!!res1.data.face && res1.data.face.data
                        .name) || '';
                      _.driverInfo.licenseSex = (!!res1.data.face && res1.data.face.data
                        .sex) || '';
                      _.driverInfo.licenseNationality = (!!res1.data.face && res1.data
                        .face.data.nationality) || '';
                      _.driverInfo.licenseValidfromdate = (!!res1.data.face && res1.data
                        .face.data.validfromdate) || '';
                      const licenseValDate = _.driverInfo.licenseValidfromdate ?
                        timestampToChineseDate(_.driverInfo.licenseValidfromdate) : '';
                      _.driverInfo.licenseValidfromdate = licenseValDate
                      _.driverInfo.licenseInitialissuedate = (!!res1.data.face && res1
                        .data.face.data.initialissuedate) || '';
                      const licenseInitDate = _.driverInfo.licenseInitialissuedate ?
                        timestampToChineseDate(_.driverInfo.licenseInitialissuedate) :
                        '';
                      _.driverInfo.licenseInitialissuedate = licenseInitDate
                      _.driverInfo.licenceIssuingAuthority = (!!res1.data.face && res1
                        .data.face.data.issueauthority) || '';
                      const licenseStartDateStr = res1.data.face.data.validperiod.split('至')[0];
                      if (!isNaN(new Date(licenseStartDateStr))) {
                        _.driverInfo.licenseStartDate = timestampToChineseDate(licenseStartDateStr)
                      } else {
                        _.driverInfo.licenseStartDate = ''
                      }
                      const initialissuedateStr = res1.data.face.data.initialissuedate
                      if (!isNaN(new Date(initialissuedateStr))) {
                        _.driverInfo.licenseFirstGetDate = timestampToChineseDate(initialissuedateStr)
                      } else {
                        _.driverInfo.licenseFirstGetDate = ''
                      }
                      _.initialDateShow = _.driverInfo.licenseFirstGetDate
                      const validperiodEnd = res1.data.face.data.validperiod
                        .split('至')[1]
                      if (validperiodEnd) {
                        if (validperiodEnd.includes('2999')) {
                          _.driverInfo.licenseEndDate = '2099-12-31';
                        } else {
                          if (!isNaN(new Date(validperiodEnd))) {
                            _.driverInfo.licenseEndDate = timestampToChineseDate(validperiodEnd)
                          } else {
                            _.driverInfo.licenseEndDate = ''
                          }
                        }
                      }
                      _.dateStart2Show = _.driverInfo.licenseStartDate
                      _.dateEnd2Show = _.driverInfo.licenseEndDate

                      _.faceUpload = true
                    } else {
                      msg = '请上传驾驶证正面'
                      iconFlag = 'none'
                      _.errorMsg = '请上传驾驶证正面'
                      _.validateno = false
                      _.imagesLicenseFace = []
                      _.driverInfo.drivingFaceUrl = undefined
                      _.faceUpload = false
                    }
                  } else if (type == 4) { //驾驶证背面
                    iconFlag = 'success'
                    _.uploadImgMess4 = false
                    _.showBackWord4 = true
                    if (!!res1.data.back) {
                      console.log('back----------', res1.data.back)
                      _.driverInfo.recordnumber = (!!res1.data.back && res1.data.back
                        .data.recordnumber) || '';
                      _.driverInfo.record = (!!res1.data.back && res1.data.back.data
                        .record) || '';
                      msg = '上传成功'
                      _.backUpload = true

                    } else {
                      msg = '请上传驾驶证背面'
                      iconFlag = 'none'
                      _.errorMsg = '请上传驾驶证背面'
                      _.validateno = false
                      _.imagesLicenseBack = []
                      _.driverInfo.drivingBackUrl = undefined
                      _.backUpload = false
                    }
                  } else {
                    _.showBackWord5 = true
                  }
                } else {
                  msg = res1.msg
                  iconFlag = 'none'
                  _.errorMsg = res1.msg
                  _.validateno = false
                  //识别失败或上传失败，就清空图片
                  if (type == 1) {
                    _.imagesPathFace = []
                    _.driverInfo.idFaceUrl = undefined
                    _.faceIdUpload = false
                  } else if (type == 2) {
                    _.imagesPathBack = []
                    _.driverInfo.idBackUrl = undefined
                    _.backIdUpload = false
                  } else if (type == 3) {
                    _.imagesLicenseFace = []
                    _.driverInfo.drivingFaceUrl = undefined
                    _.faceUpload = false
                  } else if (type == 4) {
                    _.imagesLicenseBack = []
                    _.driverInfo.drivingBackUrl = undefined
                    _.backUpload = false
                  } else {
                    _.imagesPathRoad = []
                    _.driverInfo.roadCertUrl = undefined
                    _.driverInfo.isRoadCertIdentified = false
                  }
                }
              }
              wx.hideLoading()
              toast(msg)
            } else {
              if (type == 1) _.uploadImgMess1 = true
              else if (type == 2) _.uploadImgMess2 = true
              else if (type == 3) _.uploadImgMess3 = true
              else if (type == 4) _.uploadImgMess4 = true
              else _.uploadImgMess5 = true
              if (res.statusCode === 413) {
                toast('上传图片过大，请重新上传，不要选择原图')
              } else {
                toast('上传失败，状态码:', res.statusCode)
              }
            }
          },
          fail(err) {
            wx.hideLoading()
            uni.showToast({
              title: '上传失败',
              icon: "fail"
            });
          }
        })
      },
      uploadFilesKamo(filepath, type) { //上传卡漠
        uni.uploadFile({
          url: config.baseUrl + "/queue/freight-kamo/upload",
          filePath: filepath,
          name: 'file',
          header: {
            "Content-Type": "multipart/form-data",
            'Authorization': 'Bearer ' + getAccessToken(),
          },
          success: async (res) => {
            console.log('this', this)
            if (type == 1) this.driverInfo.idCardLicenseFrontPic = JSON.parse(res.data).data;
            else if (type == 2) this.driverInfo.idCardLicenseReversePic = JSON.parse(res.data)
              .data;
            else if (type == 3) this.driverInfo.drivingLicenseFrontPic = JSON.parse(res.data).data;
            else if (type == 4) this.driverInfo.drivingLicenseReversePic = JSON.parse(res.data)
              .data;
            else this.driverInfo.qualityCertPic = JSON.parse(res.data).data;
          },
          fail(err) { }
        })
      },
      // 移出图片函数
      // async deletephotoFace() {
      // 	let that = this
      // 	that.imagesPathFace = []
      // 	that.imagesPathFace.push({
      // 		url: require("@/static/images/id-face.jpg"),
      // 		extname: '',
      // 		name: ''
      // 	})
      // },
      // 移出图片函数
      // async deletephotoBack() {
      // 	let that = this
      // 	that.imagesPathBack = []
      // 	that.imagesPathBack.push({
      // 		url: require("@/static/images/id-back.jpg"),
      // 		extname: '',
      // 		name: ''
      // 	})
      // }
    }
  };
</script>

<style lang="scss" scoped>
  .content {}
</style>